/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:lmrp-webapp
 * Create Time: 2016年4月13日 上午11:26:29
 */
package com.lenovo.lmrp.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Produces;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lenovo.lmrp.api.itsmgateway.IItsmEngineer;
import com.lenovo.lmrp.api.model.RestResponse;
import com.lenovo.lmrp.api.model.view.LoginData;
import com.lenovo.lmrp.util.RestClientFactory;
import com.lenovo.sdc.framework.common.base.BaseRestSpringController;
import com.lenovo.sdc.framework.rest.RestClientProxy;

/**
 * 
 * @author wwh
 * @version $Id: LoginContorller.java, v 0.1 2016年4月20日 上午11:26:29 wwh Exp $
 */

@Controller
public class LoginContorller extends BaseRestSpringController {
	/** binder用于bean属性的设置 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
	/**
	 * 增加了@ModelAttribute的方法可以在本controller方法调用前执行,可以存放一些共享变量,如枚举值,或是一些初始化操作
	 */
	@ModelAttribute
	public void init(ModelMap model) {
		model.put("now", new java.sql.Timestamp(System.currentTimeMillis()));
	}
	@Autowired
	RestClientFactory restClientFactory = new RestClientFactory();
	
	private static final String LOGIN_URL = "/lmrp/login";
	
	/**
     * 获取登录页面
     * @author wwh
     * @return 视图页面/WEB-INF/view/login.html
     * @throws Exception
     */
    @RequestMapping(value="/login")
    public String login() throws Exception {
        return "/login";
    }
    
    /**
     * 登录校验
     * @param itsmcode
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{itsmcode}/login",method=RequestMethod.POST)
    @ResponseBody
    @Produces({"application/json"})
    public Integer login(@PathVariable String itsmcode,@RequestParam("username") String username,
                         @RequestParam("password")String password) throws Exception{  
        Integer result = null;
        try{
            RestClientProxy itsmGatewayProxy = restClientFactory.getItsmGatewayClient();
            if(Objects.nonNull(itsmGatewayProxy)){
                IItsmEngineer iItsmEngineer = itsmGatewayProxy.getService(IItsmEngineer.class);
                if(Objects.nonNull(iItsmEngineer)){
                    LoginData loginData = new LoginData();
                    loginData.setLoginname(username);
                    loginData.setPassword(password);
                    RestResponse<Integer> authenticate  = iItsmEngineer.authenticate(itsmcode, loginData);
                    if(Objects.nonNull(authenticate)){
                        result = authenticate.getResult();//查询到结果；count为0表示查询成功               
                        if(result==0){ 
                            this.getCurrentSession().setAttribute("loginData",loginData);   	                       
                        }
                    }else{
                        log.error("error query authenticate is null");
                    }
                }else{
                    log.error("error no find IItsmEngineer.class ");
                }
            } else{
                log.error ("error ItsmGatewayProxy interface exception");
            }
        }catch(Exception e){
            log.error(e.getMessage(), e);
        }
        return result;
  }
    
    /**
     * 登出，注销用户信息
     * 
     * @param req
     * @param res
     * @throws Exception
     */
    @RequestMapping(value="/loginout",method=RequestMethod.GET)
    public void loginout(HttpServletRequest req, HttpServletResponse res)throws Exception{
        this.getCurrentSession().removeAttribute("loginData");
        if(this.getCurrentSession().getAttribute("loginData")==null){
            res.sendRedirect(LOGIN_URL);
        }
  }
}
